//
//  CollectionEnable.swift
//  CooperSwift_Example
//
//  Created by 计海峰 on 2021/5/24.
//  Copyright © 2021 CocoaPods. All rights reserved.
//

import Foundation
import UIKit
import Then
import RxSwift
import RxDataSources

private struct AssociateKeys {
    static var collection: Void?
    // 也可以直接这样写
    // static var disablePopGesture = "disablePopGesture"
}

// MARK: - collection enable
public protocol CollectionEnableProtocol : BindKeyProtocol { }


// MARK: - collection view
public extension CollectionEnableProtocol {
    
    var collectionView: UICollectionView {
        get {
            return associatedObject(forKey: &AssociateKeys.collection, default: collectionV(), ploicy: .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        set {
            objc_setAssociatedObject(self, &AssociateKeys.collection, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    @discardableResult
    private func collectionV() -> UICollectionView {
        collectionView = UICollectionView.init(frame: CGRect(0, 0, Screen.width, Screen.height), collectionViewLayout: UICollectionViewFlowLayout.init().defaultLayout()).then {
            $0.backgroundColor = .white
            $0.showsVerticalScrollIndicator = false;
            $0.showsHorizontalScrollIndicator = false;
            $0.contentInsetAdjustmentBehavior = .never
        }
        return collectionView
    }
}

// MARK: - 配置上拉下拉
//public extension Refreshable where Self: NSObject & CollectionEnableProtocol {
//    func updateRefresh<T: RefreshControllable & CollectionViewModelProtocol & NSObject >(_ vm: T, bag: DisposeBag, refreshConfig config: ScrollViewRefreshEnum) {
//        
//        self.rx.refresh(vm, collectionView).subscribe(onNext: {
//            switch $0 {
//            case .header:
//                vm.refresh()
//            case .footer:
//                vm.pull()
//            }
//        }).disposed(by: bag)
//        
//        switch config {
//        case .none:
//            vm.rx.refreshStatus.onNext(.hiddenHeader)
//            vm.rx.refreshStatus.onNext(.hiddenFooter)
//        case .header:
//            vm.rx.refreshStatus.onNext(.hiddenFooter)
//        case .footer:
//            vm.rx.refreshStatus.onNext(.hiddenHeader)
//        case .all: break
//        }
//        
//    }
//}

// MARK: - 绑定 viewmodel
extension CollectionEnableProtocol {
    
    
    func bindVM(_ vm: CollectionViewModelProtocol, bag: DisposeBag) {
        
        /// 初始化结束
        vm.initDown()
        
        /// collectionView 获取
        let cv = collectionView
        
        /// collectionview 数据源
        let dataSource: RxCollectionViewSectionedReloadDataSource = vm.configDataSource()
        
        /// 防抖节流
        vm.sectionsSubject.debounce(.milliseconds(300), scheduler: MainScheduler.instance).bind(to: cv.rx.items(dataSource: dataSource)).disposed(by: bag)
        
        /// 固定时间刷新节流
//        vm.sectionsSubject.throttle(.milliseconds(300), latest: true, scheduler: MainScheduler.instance).bind(to: cv.rx.items(dataSource: dataSource)).disposed(by: bag)
        
        // 绑定key
        vm.bindKey(bag)
        vm.parentKey = bindKey()
        
        // 部分已写服务
        if let vc = self as? UIViewController {
            
            vm.configServicBlock { [weak vc] service in
                switch service {
                case .controller:
                    return self
    
                case .collection:
                    return cv
    
                case .view:
                    return vc?.view
    
                case .all:
                    return (vc, vc?.view, cv)
    
                case .reloadCollection:
                    cv.reloadData()
                    return nil
    
                case .endEdit:
                    vc?.view.endEditing(true)
                    cv.endEditing(true)
                    return nil
    
                }
    
            }
        }
        
        // delegate 代理
        if let delegate = vm as? UICollectionViewDelegate {
            cv.rx.setDelegate(delegate).disposed(by: bag)
        }
        
        // 配置结束
        vm.configDown()
        
    }
    
}

// MARK: - collection for view controller
public extension CollectionEnableProtocol where Self : UIViewController {
    
    /// 绑定collectionview
    /// - Parameter edges: 边距
    func configCollection(_ edges: UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: -Screen.bottomBarHeight, right: 0), layout: UICollectionViewFlowLayout? = nil) {
        bgColor(.white)
        if let lay = layout {
            collectionView.collectionViewLayout = lay
        }
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.edges.equalTo(view).inset(edges)
        }
    }
 
}

// MARK: - collection for view
public extension CollectionEnableProtocol where Self : UIView {
    
    /// 绑定collectionview
    /// - Parameter edges: 边距
    func configCollection(_ edges: UIEdgeInsets = UIEdgeInsets.zero, layout: UICollectionViewFlowLayout? = nil) {
        if let lay = layout {
            collectionView.collectionViewLayout = lay
        }
        addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview().inset(edges)
        }
    }
    
}


public extension CollectionEnableProtocol {
    
    /// 配置collectionview
    /// - Parameters:
    ///   - vm: viewmodel
    ///   - disposeBag: 销毁包
    ///   - config: 刷新配置
    func configAll(_ vm: CollectionViewModelProtocol, disposeBag: DisposeBag, edges: UIEdgeInsets = UIEdgeInsets.zero, flowLayout: UICollectionViewFlowLayout? = nil) {
        /// 配置collection
        if let vc = self as? (UIViewController & CollectionEnableProtocol) {
            vc.configCollection(edges, layout: flowLayout)
//            vc.configCollection(layout: flowLayout)
        }else
        if let v = self as? (UIView & CollectionEnableProtocol) {
            v.configCollection(edges, layout: flowLayout)
//            v.configCollection(layout: flowLayout)
        }
        /// 绑定key 并且添加通知
        bindKey(disposeBag)
        /// 绑定view model
        bindVM(vm, bag: disposeBag)
        
        /// rx 来自 public extension Refreshable where Self: NSObject & TableEnableProtocol
        rx.tapEmptyButton(collectionView) { _ in
            vm.refresh()
        }
        
    }
    
}

// MARK: - 配置上拉下拉
public extension Refreshable where Self: CollectionEnableProtocol {
    func updateRefresh<T: RefreshControllable & CollectionViewModelProtocol >(_ vm: T, bag: DisposeBag, refreshConfig config: ScrollViewRefreshEnum) {
        switch config {
        case .none:
            vm.rx.refreshStatus.onNext(.hiddenHeader)
            vm.rx.refreshStatus.onNext(.hiddenFooter)
        case .header:
            vm.rx.refreshStatus.onNext(.hiddenFooter)
        case .footer:
            vm.rx.refreshStatus.onNext(.hiddenHeader)
        case .all: break
        }
    }
}

// 下拉上拉 直接 配置 collection
public extension CollectionEnableProtocol where Self: Refreshable {
    
    /// 配置collectionview
    /// - Parameters:
    ///   - vm: viewmodel
    ///   - disposeBag: 销毁包
    ///   - config: 刷新配置
    func configAll<T: RefreshControllable & CollectionViewModelProtocol >(_ vm: T, disposeBag: DisposeBag, refreshConfig config: ScrollViewRefreshEnum = .none, edges: UIEdgeInsets = UIEdgeInsets.zero, flowLayout: UICollectionViewFlowLayout? = nil) {
        
        self.configAll(vm, disposeBag: disposeBag, edges: edges, flowLayout: flowLayout)
        self.rx.updateRefresh(vm, scrollview: collectionView, bag: disposeBag, refreshConfig: config)
        
    }
    
}
